import time
from threading import Timer

from parser import FormParser,LoginParser,AbstractParser
from eventmanager import EventManager,Topic,Singleton
from constants import ParserStatus


class RapidshareParser (FormParser):
    
    
    def __init__(self,url,premium = False):
        FormParser.__init__(self,
                            url = url,
                            premium = premium)
        self.__statusParser = None 
        self.fileName = url.split('/')[-1]
        e = EventManager()
        self.errorTopic = e.getTopic('errorTopic')
        
        
        """
        Status pattern gives different
        behaviors for the same function depending 
        of the type of the __statusParser attribute
        """
        if "This file is suspected to contain illegal" in self.plainHTML:
            self.errorTopic.publish('File %s suspended' % self.fileName)
        
        else:
            if self.premium == True:
                self.__statusParser = PremiumRapidshare(self.forms[1].request())
            else:
                self.__statusParser = AnonymousRapidshare(self.forms[0].request())

    def getDirectLink(self):
        return self.__statusParser.getDirectLink()

    def getWaitingTime(self):
        return self.__statusParser.getWaitingTime()

    def __str__(self):
        ret = 'Rapidshare Parser: %s\n' % self.fileName
        ret += 'Link: %s Time: %s\n' % (self.getDirectLink(),
                                        self.getWaitingTime())

        
        return ret

    def __repr__(self):
        return self.__str__()

class PremiumRapidshare (FormParser):
    
    
    def __init__(self,handle):
        FormParser.__init__(self,
                            handle = handle,
                            premium = True)
        e = EventManager()
        self.errorTopic = e.getTopic('errorTopic')
        self.startTopic = e.getTopic('startDownloadTopic')

        self.__waitingTime = 0
        url = handle.geturl()
        self.fileName = url.split('/')[-1]
        t = Timer(self.getWaitingTime(),self.endWaiting)
        t.start()
    
    def getWaitingTime(self):
        return self.__waitingTime
    
    def getDirectLink (self):
        return self.forms[1].getAction()
    
    
    def endWaiting(self):
        print 'endWaiting, %s' % self.getDirectLink()
        self.__status = ParserStatus.Complete
        self.startTopic.publish(self.getDirectLink(),
                                self.fileName)


    def __str__(self):
        pass


class AnonymousRapidshare (FormParser):
    

    def __init__(self,handle):
        FormParser.__init__(self,handle=handle)
        self.__status = ParserStatus.Parsing
        e = EventManager()
        self.errorTopic = e.getTopic('errorTopic')
        self.startTopic = e.getTopic('startDownloadTopic')
        url = handle.geturl()
        self.fileName = url.split('/')[-1]
        self.__directLink = ''
        self.__computeInitialTime()

                
    def __computeInitialTime(self):
        for line in self.plainHTML.split('\n'):
            if "var c" in line:
                self.__initialTime = float(line.split('=')[1].strip()[:-1])
                self.__startWaitingTime = time.time()
                t = Timer(self.getWaitingTime(),self.endWaiting)
                t.start()
            if "Currently a lot of users are downloading files" in line or \
                    "There are no more download slots available for free users right now" in line:
                self.__status = ParserStatus.Error
                self.errorTopic.publish('Satured service')
                break
            if "var tt" in line:
                self.__directLink = line.split('=')[3].split('"')[1]

    def endWaiting(self):
        print 'endWaiting, %s' % self.__directLink
        self.__status = ParserStatus.Complete
        self.startTopic.publish(self.__directLink,
                                self.fileName)

    def getStatus(self):
        return self.__status
                
    def getWaitingTime(self):
        elapsed = time.time()-self.__startWaitingTime

        remaining = self.__initialTime-elapsed


        if remaining < 0:
            remaining = 0
        return remaining

    def getDirectLink(self):
        return self.__directLink
        
                
    
class RapidshareLogin(LoginParser):
    
    def __init__(self,user,password):
        url = 'https://ssl.rapidshare.com/premiumzone.html'
        LoginParser.__init__(self,user,password,url)
        self.__login()
        
    def __login(self):
        loginform = self.forms[0]
        inputs = loginform.getInputs()
        userInput = inputs[1]
        userInput.value = self.user
        passwordInput = inputs[2]
        passwordInput.value = self.password
        handle = loginform.request()
        AbstractParser(premium=True,handle=handle)
        

    
